//
//  KLMBaseRowController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/4.
//

import UIKit

// 定义标题接收协议
protocol RowTitleReceivable: AnyObject {
    var titleText: String? { get set }
}

private let cellId = String(describing: KLMBaseRowItemCell.self)

class KLMBaseRowController: KLMBaseController, KLMBaseRowItemCellDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    
    var lastIndexPath: IndexPath?
    // 子类必须提供的表格数据
    var rowItems: [[KLMRowItem]] = []
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        if nibNameOrNil != nil {
            super.init(nibName: nibNameOrNil, bundle: nil)
        } else {
            super.init(nibName: "KLMBaseRowController", bundle: nil)
        }
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = titleText
    }
    
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        
        if tableView != nil {
            tableView.separatorStyle = .none
            tableView.register(UINib(nibName: "KLMBaseRowItemCell", bundle: nil), forCellReuseIdentifier: cellId)
            tableView.dataSource = self
            tableView.delegate = self
        }
    }
    override func setNavBarStyle() {
        customNavBarAppearance(barTintColor: .white, titleColor: nil)
    }
    func tableViewDidSelect(item: KLMRowItem, at: IndexPath, on: UITableView) -> Void {
        print("点击了\(item.title ?? "")")
    }
    func tableViewConfigLastCell(item: KLMRowItem, at: IndexPath, on: UITableView) -> Void {
        print("上一个cell：\(item.title ?? "")")
    }
    
    func rowItemCellToggleOn(cell: KLMBaseRowItemCell, index: IndexPath, on tableView: UITableView) {
        var item = rowItems[index.section][index.row]
        item.isOn = !item.isOn
        rowItems[index.section][index.row] = item
        tableView.reloadRows(at: [index], with: .fade)
    }
    func rowItemCellTapArrowBtn(cell: KLMBaseRowItemCell, index: IndexPath, on tableView: UITableView) {}
    func rowItemCellTapRightBtn(cell: KLMBaseRowItemCell, index: IndexPath, on tableView: UITableView) {}
}

extension KLMBaseRowController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return rowItems.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let section = rowItems[section]
        return section.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = KLMBaseRowItemCell.cell(with: tableView, at: indexPath, cellId: cellId)
        cell.item = rowItems[indexPath.section][indexPath.row]
        cell.delegate = self
        return cell
    }
}

extension KLMBaseRowController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UIView.animate(withDuration: 1.0) {
            tableView.deselectRow(at: indexPath, animated: true)
        }
        if let last = lastIndexPath, last != indexPath {
            tableViewConfigLastCell(item: rowItems[last.section][last.row], at: last, on: tableView)
        }
        tableViewDidSelect(item: rowItems[indexPath.section][indexPath.row], at: indexPath, on: tableView)
        
        lastIndexPath = indexPath
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 16
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == rowItems.count - 1 {
            return 0
        } else {
            return 16
        }
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == rowItems.count - 1 {
            return nil
        } else {
            let view = UIView()
            let line = UIView(frame: CGRect(x: 16, y: 15, width: tableView.width - 2*16, height: 1))
            line.backgroundColor = rgba(242, 242, 242, 1)
            view.addSubview(line)
            return view
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56
    }
}
